package provider_mem

import (
	"errors"
	"strings"

	"gitee.com/kobeyyf/apibox/middleware/httpsign"
	"github.com/spf13/viper"
)

const (
	name = "mem"
)

func init() {
	httpsign.AddSecretProvider(name, &SecretProviderMem{})
}

type SecretProviderMem struct {
	secretMap map[string]string
}

func (p *SecretProviderMem) GetSecret(key string) (secret string, has bool) {
	secret, has = p.secretMap[key]
	return
}

func (p *SecretProviderMem) Init(c *viper.Viper) (err error) {
	secrets := c.GetStringSlice("apisign.secret")
	if len(secrets) == 0 {
		return errors.New("apisign.secret is empty")
	}
	p.secretMap = make(map[string]string, len(secrets))
	for _, secret := range secrets {
		slice := strings.SplitN(secret, ",", 2)
		p.secretMap[slice[0]] = slice[1]
	}
	return nil
}
